/**
 * Must have a length of at least 8 characters
 * @type {String}
 *
 * @properties={typeid:35,uuid:"106392D8-102D-431D-97FD-701C80EDD907"}
 */
var cryptKey = 'InF0ComSA4831';

/**
 * @param {String} _string
 * @param {String} _encoding
 *
 * @properties={typeid:24,uuid:"00AADC46-40EF-49C8-AA54-EDD42EC39680"}
 */
function StringToBytes(_string, _encoding) {
	if (!_encoding) {
		_encoding = "UTF-8";
	}
	return new Packages.java.lang.String(_string).getBytes(_encoding);
}

/**
 * @param {String} _key
 *
 * @properties={typeid:24,uuid:"6903D674-E137-4E1C-8EC2-99EFF06E6A73"}
 */
function getKey(_key) {
	var _bytes 		= StringToBytes(_key, "UTF-8");
	var _pass 		= new Packages.javax.crypto.spec.DESKeySpec(_bytes);
	var _skf 		= Packages.javax.crypto.SecretKeyFactory.getInstance("DES");
	var _secretKey 	= _skf.generateSecret(_pass);
	return _secretKey;
}

/**
 * @param {String} _string
 * @param {String} _key
 * @param {String} _operation (D=Descrypt / C=Crypt
 *
 * @properties={typeid:24,uuid:"86F53F35-8C30-4994-9F24-4F50B1B2E849"}
 */
function cryptString(_string, _key, _operation) {
	var _secretKey 	= getKey(_key);
	var _base64 	= Packages.org.apache.commons.codec.binary.Base64;
	var _desCipher 	= Packages.javax.crypto.Cipher.getInstance("DES/ECB/PKCS5Padding");
	var _ciphertext, _clearText;

	if (_operation == "C") {
		// --- Crypt.
		_desCipher.init(Packages.javax.crypto.Cipher.ENCRYPT_MODE, _secretKey);
		_clearText = StringToBytes(_string, "UTF-8");
		_ciphertext = _desCipher.doFinal(_clearText);
		return _base64.encodeBase64String(_ciphertext);
	} else if (_operation == "D") {
		// --- Decrypt
		_ciphertext = _base64.decodeBase64(_string);
		_desCipher.init(Packages.javax.crypto.Cipher.DECRYPT_MODE, _secretKey);
		_clearText = _desCipher.doFinal(_ciphertext);
		/** @type String*/
		var _textDecoded = new Packages.java.lang.String(_clearText)
		return (_textDecoded);
	} else {
		return "Invalid Operation";
	}
}
